<?php
/*
Template Name: User Center
*/

// Redirect to login page if user is not logged in
if (!is_user_logged_in()) {
    wp_redirect(wp_login_url(get_permalink()));
    exit;
}

$current_user = wp_get_current_user();

// Get user stats
$user_id = $current_user->ID;

// Get favorites count
$favorite_posts = get_user_meta($user_id, '_favorite_posts', true);
$favorites_count = is_array($favorite_posts) ? count($favorite_posts) : 0;

// Get read posts count
// NOTE: This requires the tracking functionality to be added to theme-single.php
$read_posts = get_user_meta($user_id, '_read_posts', true);
$read_count = is_array($read_posts) ? count($read_posts) : 0;

// Get comments count
$comments_count = get_comments(array('user_id' => $user_id, 'count' => true));

// Get notifications
$notifications = get_user_meta($user_id, '_user_notifications', true);
if (!is_array($notifications)) {
    $notifications = [];
}
$unread_notifications_count = count(array_filter($notifications, function($n) {
    return !$n['is_read'];
}));

get_header();
?>

<!-- 主内容区 -->
<main class="flex-grow pt-24 pb-16">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <!-- 面包屑导航 -->
        <div class="mb-8 animate-fade-in">
            <nav class="text-sm text-neutral-500">
                <a href="<?php echo home_url(); ?>" class="hover:text-primary transition-colors">首页</a>
                <i class="fa fa-angle-right mx-2 text-xs"></i>
                <span class="text-neutral-700">用户中心</span>
            </nav>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
            <!-- 侧边栏 -->
            <div class="lg:col-span-1 space-y-6 animate-slide-up">
                <!-- 用户信息卡片 -->
                <div class="bg-white rounded-2xl shadow-lg overflow-hidden">
                    <div class="bg-gradient-primary h-32 relative">
                        <div class="absolute inset-0 bg-black/20"></div>
                        <div class="absolute bottom-0 left-0 w-full p-4">
                            <div class="flex items-end space-x-3">
                                <div class="w-16 h-16 rounded-full border-4 border-white overflow-hidden">
                                    <?php echo get_avatar($current_user->ID, 96, '', '', array('class' => 'w-full h-full object-cover')); ?>
                                </div>
                                <div>
                                    <h3 class="text-white font-bold text-lg"><?php echo esc_html($current_user->display_name); ?></h3>
                                    <div class="text-white/80 text-sm flex items-center">
                                        <span class="mr-2">注册于 <?php echo date('Y-m-d', strtotime($current_user->user_registered)); ?></span>
                                        <?php
                                        $user_roles = $current_user->roles;
                                        $user_role = !empty($user_roles) ? $user_roles[0] : '';
                                        if ($user_role) {
                                            echo '<span class="bg-white/20 px-2 py-0.5 rounded text-xs">' . esc_html(ucfirst($user_role)) . '</span>';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="p-4 pt-8">
                        <div class="grid grid-cols-3 gap-2 text-center mb-6">
                            <div>
                                <div class="font-bold text-lg"><?php echo $favorites_count; ?></div>
                                <div class="text-sm text-neutral-500">收藏</div>
                            </div>
                            <div>
                                <div class="font-bold text-lg"><?php echo $comments_count; ?></div>
                                <div class="text-sm text-neutral-500">评论</div>
                            </div>
                            <div>
                                <div class="font-bold text-lg"><?php echo $read_count; ?></div>
                                <div class="text-sm text-neutral-500">阅读</div>
                            </div>
                        </div>
                        
                        <a href="#settings" class="user-center-nav-link w-full flex items-center justify-center space-x-2 py-2 px-4 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors">
                            <i class="fa fa-pencil"></i>
                            <span>编辑资料</span>
                        </a>
                    </div>
                </div>
                
                <!-- 导航菜单 -->
                <div class="bg-white rounded-2xl shadow-lg p-4 animate-slide-up" style="animation-delay: 0.1s">
                    <h4 class="text-lg font-bold text-neutral-800 mb-4">导航菜单</h4>
                    <nav class="space-y-1" id="user-center-nav">
                        <a href="#profile" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors active">
                            <i class="fa fa-user-o w-5 mr-3"></i>
                            <span>个人资料</span>
                        </a>
                        <a href="#favorites" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors">
                            <i class="fa fa-heart-o w-5 mr-3"></i>
                            <span>我的收藏</span>
                        </a>
                        <a href="#reading-history" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors">
                            <i class="fa fa-history w-5 mr-3"></i>
                            <span>阅读历史</span>
                        </a>
                        <a href="#comments" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors">
                            <i class="fa fa-comment-o w-5 mr-3"></i>
                            <span>我的评论</span>
                        </a>
                        <a href="#notifications" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors relative">
                            <i class="fa fa-bell-o w-5 mr-3"></i>
                            <span>消息通知</span>
                            <?php if ($unread_notifications_count > 0) : ?>
                                <span class="absolute top-1 right-2 w-2 h-2 bg-red-500 rounded-full"></span>
                            <?php endif; ?>
                        </a>
                        <a href="#settings" class="user-center-nav-link flex items-center px-4 py-2 text-neutral-600 rounded-lg hover:bg-neutral-100 hover:text-primary transition-colors">
                            <i class="fa fa-cog w-5 mr-3"></i>
                            <span>账号设置</span>
                        </a>
                        <a href="<?php echo wp_logout_url(home_url()); ?>" class="flex items-center px-4 py-2 text-red-500 rounded-lg hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-sign-out w-5 mr-3"></i>
                            <span>退出登录</span>
                        </a>
                    </nav>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="lg:col-span-3 space-y-8" id="user-center-content">

                <!-- 欢迎卡片 -->
                <div class="bg-gradient-primary rounded-2xl shadow-lg overflow-hidden relative animate-slide-up">
                    <div class="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full -mr-32 -mt-32"></div>
                    <div class="absolute bottom-0 left-0 w-48 h-48 bg-white/5 rounded-full -ml-24 -mb-24"></div>
                    
                    <div class="p-6 md:p-8 relative z-10">
                        <h2 class="text-2xl font-bold text-white mb-2">欢迎回来，<?php echo esc_html($current_user->display_name); ?></h2>
                        <p class="text-white/80 mb-6">今天是 <?php echo date_i18n('Y年n月j日，l'); ?>。</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                                <div class="flex items-center space-x-3 mb-2">
                                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                                        <i class="fa fa-bookmark-o text-white"></i>
                                    </div>
                                    <h3 class="text-white font-medium">我的收藏</h3>
                                </div>
                                <p class="text-white/80 text-sm">你收藏了 <?php echo $favorites_count; ?> 篇文章</p>
                                <a href="#favorites" class="user-center-nav-link inline-block mt-3 text-white text-sm hover:underline">查看全部</a>
                            </div>
                            
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                                <div class="flex items-center space-x-3 mb-2">
                                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                                        <i class="fa fa-history text-white"></i>
                                    </div>
                                    <h3 class="text-white font-medium">阅读历史</h3>
                                </div>
                                <p class="text-white/80 text-sm">你最近阅读了 <?php echo $read_count; ?> 篇文章</p>
                                <a href="#reading-history" class="user-center-nav-link inline-block mt-3 text-white text-sm hover:underline">查看全部</a>
                            </div>
                            
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                                <div class="flex items-center space-x-3 mb-2">
                                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                                        <i class="fa fa-comment-o text-white"></i>
                                    </div>
                                    <h3 class="text-white font-medium">我的评论</h3>
                                </div>
                                <p class="text-white/80 text-sm">你发表了 <?php echo $comments_count; ?> 条评论</p>
                                <a href="#comments" class="user-center-nav-link inline-block mt-3 text-white text-sm hover:underline">查看全部</a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 个人资料 -->
                <div id="profile" class="user-center-panel bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <h3 class="text-2xl font-bold text-neutral-800 mb-6">个人资料</h3>
                    <div class="space-y-6">
                        <div class="flex items-center">
                            <label class="w-32 text-neutral-500">用户名</label>
                            <span><?php echo esc_html($current_user->user_login); ?></span>
                        </div>
                        <div class="flex items-center">
                            <label class="w-32 text-neutral-500">昵称</label>
                            <span><?php echo esc_html($current_user->display_name); ?></span>
                        </div>
                        <div class="flex items-center">
                            <label class="w-32 text-neutral-500">邮箱</label>
                            <span><?php echo esc_html($current_user->user_email); ?></span>
                        </div>
                        <div class="flex items-center">
                            <label class="w-32 text-neutral-500">注册时间</label>
                            <span><?php echo date('Y-m-d H:i:s', strtotime($current_user->user_registered)); ?></span>
                        </div>
                        <div class="flex items-start">
                            <label class="w-32 text-neutral-500 pt-1">个人简介</label>
                            <p class="flex-1"><?php echo esc_html($current_user->description) ?: '暂无简介'; ?></p>
                        </div>
                    </div>
                </div>

                <!-- 我的收藏 -->
                <div id="favorites" class="user-center-panel hidden bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <h3 class="text-2xl font-bold text-neutral-800 mb-6">我的收藏</h3>
                    <div id="favorites-list" class="space-y-4">
                        <?php
                        if ($favorite_posts && !empty($favorite_posts)) {
                            foreach ($favorite_posts as $post_id) {
                                $post = get_post($post_id);
                                if ($post) {
                        ?>
                                    <div class="flex items-center p-4 border border-neutral-200 rounded-lg hover:shadow-md transition-shadow" data-post-id="<?php echo $post_id; ?>">
                                        <div class="flex-grow">
                                            <a href="<?php echo get_permalink($post_id); ?>" class="font-semibold text-neutral-800 hover:text-primary"><?php echo esc_html($post->post_title); ?></a>
                                            <p class="text-sm text-neutral-500 mt-1">收藏于 <?php echo get_the_date('Y-m-d', $post_id); ?></p>
                                        </div>
                                        <button class="remove-favorite-btn px-3 py-1 text-sm text-red-500 border border-red-200 rounded-full hover:bg-red-50" data-post-id="<?php echo $post_id; ?>" data-nonce="<?php echo wp_create_nonce('wanzicms_interactions_nonce'); ?>">取消收藏</button>
                                    </div>
                        <?php
                                }
                            }
                        } else {
                            echo '<p class="text-center text-neutral-500 pt-4">没有更多收藏了</p>';
                        }
                        ?>
                    </div>
                </div>

                <!-- 阅读历史 -->
                <div id="reading-history" class="user-center-panel hidden bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <h3 class="text-2xl font-bold text-neutral-800 mb-6">阅读历史</h3>
                    <div class="space-y-4">
                        <?php
                        if ($read_posts && !empty($read_posts)) {
                            // Reverse the array to show the latest read posts first
                            $read_posts_reversed = array_reverse($read_posts);
                            foreach ($read_posts_reversed as $post_id) {
                                $post = get_post($post_id);
                                if ($post) {
                        ?>
                                    <div class="flex items-center p-4 border border-neutral-200 rounded-lg hover:shadow-md transition-shadow">
                                        <div class="flex-grow">
                                            <a href="<?php echo get_permalink($post_id); ?>" class="font-semibold text-neutral-800 hover:text-primary"><?php echo esc_html($post->post_title); ?></a>
                                            <p class="text-sm text-neutral-500 mt-1">阅读于 <?php echo get_the_date('Y-m-d', $post_id); ?></p>
                                        </div>
                                    </div>
                        <?php
                                }
                            }
                        } else {
                            echo '<p class="text-center text-neutral-500 pt-4">你还没有阅读过任何文章。</p>';
                        }
                        ?>
                    </div>
                </div>

                <!-- 我的评论 -->
                <div id="comments" class="user-center-panel hidden bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <h3 class="text-2xl font-bold text-neutral-800 mb-6">我的评论</h3>
                    <div class="space-y-6">
                        <?php
                        $user_comments = get_comments(array('user_id' => $user_id, 'number' => 10, 'status' => 'approve'));
                        if ($user_comments) {
                            foreach ($user_comments as $comment) {
                        ?>
                                <div class="p-4 border border-neutral-200 rounded-lg">
                                    <p class="text-neutral-700 mb-2"><?php echo esc_html($comment->comment_content); ?></p>
                                    <div class="text-sm text-neutral-500">
                                        <span>评论于《<a href="<?php echo get_permalink($comment->comment_post_ID); ?>#comment-<?php echo $comment->comment_ID; ?>" class="hover:text-primary"><?php echo get_the_title($comment->comment_post_ID); ?></a>》</span>
                                        <span class="mx-2">&middot;</span>
                                        <span><?php echo date('Y-m-d H:i', strtotime($comment->comment_date)); ?></span>
                                    </div>
                                </div>
                        <?php
                            }
                        } else {
                            echo '<p class="text-center text-neutral-500 pt-4">你还没有发表过任何评论。</p>';
                        }
                        ?>
                    </div>
                </div>

                <!-- 消息通知 -->
                <div id="notifications" class="user-center-panel hidden bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-2xl font-bold text-neutral-800">消息通知</h3>
                        <?php if (!empty($notifications)) : ?>
                        <button id="mark-all-read-btn" class="text-sm text-primary hover:underline" data-nonce="<?php echo wp_create_nonce('mark_notifications_read_nonce'); ?>">全部标记为已读</button>
                        <?php endif; ?>
                    </div>
                    <div id="notifications-list" class="space-y-4">
                         <?php
                        if (!empty($notifications)) {
                            foreach ($notifications as $notification) {
                        ?>
                                <div class="notification-item p-4 border border-neutral-200 rounded-lg <?php echo !$notification['is_read'] ? 'bg-blue-50' : ''; ?>" data-id="<?php echo esc_attr($notification['id']); ?>">
                                    <div class="flex justify-between items-start">
                                        <div class="flex-grow">
                                            <div class="text-neutral-800"><?php echo wp_kses_post($notification['message']); ?></div>
                                            <p class="text-sm text-neutral-600 mt-1"><?php echo esc_html($notification['content']); ?></p>
                                            <div class="text-xs text-neutral-400 mt-2">
                                                <span><?php echo human_time_diff($notification['timestamp'], current_time('timestamp')); ?>前</span>
                                                <span class="mx-1">&middot;</span>
                                                <a href="<?php echo esc_url($notification['link']); ?>" class="hover:text-primary">查看详情</a>
                                            </div>
                                        </div>
                                         <?php if (!$notification['is_read']) : ?>
                                            <div class="w-2.5 h-2.5 bg-primary rounded-full ml-4 mt-1 flex-shrink-0" title="未读"></div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                        <?php
                            }
                        } else {
                            echo '<p class="text-center text-neutral-500 pt-4">没有新的通知。</p>';
                        }
                        ?>
                    </div>
                </div>

                <!-- 账号设置 -->
                <div id="settings" class="user-center-panel hidden bg-white rounded-2xl shadow-lg p-8 animate-slide-up" style="animation-delay: 0.1s;">
                    <h3 class="text-2xl font-bold text-neutral-800 mb-6">账号设置</h3>
                    <form id="user-profile-form" action="" method="post">
                        <?php wp_nonce_field('update-user_' . $current_user->ID); ?>
                        <input type="hidden" name="action" value="update-user-profile">
                        <div class="space-y-6">
                            <div class="flex items-center">
                                <label for="display_name" class="w-32 text-neutral-500">昵称</label>
                                <input type="text" id="display_name" name="display_name" value="<?php echo esc_attr($current_user->display_name); ?>" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>
                            <div class="flex items-center">
                                <label for="user_email" class="w-32 text-neutral-500">邮箱</label>
                                <input type="email" id="user_email" name="user_email" value="<?php echo esc_attr($current_user->user_email); ?>" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" required>
                            </div>
                            <div class="flex items-start">
                                <label for="description" class="w-32 text-neutral-500 pt-2">个人简介</label>
                                <textarea id="description" name="description" rows="4" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"><?php echo esc_textarea($current_user->description); ?></textarea>
                            </div>
                            <div class="flex items-center">
                                <label for="pass1" class="w-32 text-neutral-500">新密码</label>
                                <input type="password" id="pass1" name="pass1" autocomplete="new-password" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="留空则不修改">
                            </div>
                            <div class="flex items-center">
                                <label for="pass2" class="w-32 text-neutral-500">确认新密码</label>
                                <input type="password" id="pass2" name="pass2" autocomplete="new-password" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="留空则不修改">
                            </div>
                            <div class="pt-4 flex justify-end">
                                <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">保存更改</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const navLinks = document.querySelectorAll('.user-center-nav-link');
    const contentPanels = document.querySelectorAll('#user-center-content .user-center-panel');
    const navContainer = document.getElementById('user-center-nav');

    function switchPanel(hash) {
        // Update nav links style
        navContainer.querySelectorAll('a').forEach(link => {
            if (link.getAttribute('href') === hash) {
                link.classList.add('active', 'bg-neutral-100', 'text-primary');
            } else {
                link.classList.remove('active', 'bg-neutral-100', 'text-primary');
            }
        });

        contentPanels.forEach(panel => {
            if ('#' + panel.id === hash) {
                panel.classList.remove('hidden');
            } else {
                panel.classList.add('hidden');
            }
        });
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const hash = this.getAttribute('href');
            if(hash.startsWith('#')) {
                e.preventDefault();
                switchPanel(hash);
                history.pushState(null, '', hash);
            }
        });
    });

    window.addEventListener('popstate', function() {
        const currentHash = window.location.hash || '#profile';
        switchPanel(currentHash);
    });

    const initialHash = window.location.hash || '#profile';
    switchPanel(initialHash);

    // Handle remove favorite
    document.getElementById('favorites-list').addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-favorite-btn')) {
            const button = e.target;
            const postId = button.dataset.postId;
            const nonce = button.dataset.nonce;
            const favoriteItem = button.closest('[data-post-id]');

            const formData = new FormData();
            formData.append('action', 'post_favorite');
            formData.append('post_id', postId);
            formData.append('nonce', nonce);

            fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.status === 'unfavorited') {
                    favoriteItem.style.transition = 'opacity 0.5s';
                    favoriteItem.style.opacity = '0';
                    setTimeout(() => {
                        favoriteItem.remove();
                        if (document.getElementById('favorites-list').children.length === 0) {
                            document.getElementById('favorites-list').innerHTML = '<p class="text-center text-neutral-500 pt-4">没有更多收藏了</p>';
                        }
                    }, 500);
                } else {
                    alert(data.data.message || '操作失败，请重试。');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请稍后重试。');
            });
        }
    });

    // Handle mark all notifications as read
    const markAllReadBtn = document.getElementById('mark-all-read-btn');
    if (markAllReadBtn) {
        markAllReadBtn.addEventListener('click', function() {
            const nonce = this.dataset.nonce;

            const formData = new FormData();
            formData.append('action', 'mark_all_notifications_read');
            formData.append('nonce', nonce);

            fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Remove unread indicators
                    document.querySelectorAll('.notification-item').forEach(item => {
                        item.classList.remove('bg-blue-50');
                    });
                    document.querySelectorAll('.notification-item .w-2\\.5').forEach(dot => {
                        dot.remove();
                    });
                    // Hide the unread count in the nav
                    const navIndicator = document.querySelector('.user-center-nav-link[href="#notifications"] .w-2');
                    if(navIndicator) navIndicator.remove();
                    
                    // Disable button after clicking
                    this.remove();
                } else {
                    alert(data.data.message || '操作失败，请重试。');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请稍后重试。');
            });
        });
    }
});
</script>

<?php
get_footer(); 